package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     * 新增菜品和对应的口味
     */
    @Transactional
    public void saveWithFlavor(DishDTO DishDTO) {
        //向数据库添加时使用entity，而不是dto
        Dish dish = new Dish();
        BeanUtils.copyProperties(DishDTO, dish);
        //1. 向菜品表新增一条数据
        dishMapper.insert(dish);

        //2. 向菜品口味表新增多条数据

        //获取生成的主键值
        Long id = dish.getId();

        //添加
        List<DishFlavor> flavors = DishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 分页查询
     *
     * @return Page DishVO 注意不是dish，因为包括菜品和口味
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        try (Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO)) {
            return new PageResult(page.getTotal(), page.getResult());
        }
    }

    /**
     * 用户端：根据分类id查询菜品
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 查询菜品
        List<Dish> dishList = dishMapper.list(dish);

        // 最终向前端返回菜品及对应口味
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            //1. 先将菜品信息添加到DishVO中
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //2. 再将查询到菜品的口味添加到DishVO中
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

}
